package log

import (
	"io"
	"os"

	"github.com/dale-di/lumberjack"
	"github.com/rs/zerolog"
	"github.com/rs/zerolog/pkgerrors"
)

var Logger zerolog.Logger

func New(logfile, level string, args ...int) {

	zerolog.TimeFieldFormat = "2006-01-02 15:04:05"
	zerolog.ErrorStackMarshaler = pkgerrors.MarshalStack
	var w io.Writer
	switch logfile {
	case "stdout":
		w = os.Stdout
	case "stderr":
		w = os.Stderr
	default:
		lj := &lumberjack.Logger{
			Filename:   logfile,
			MaxSize:    100, // megabytes
			MaxBackups: 10,
			// MaxAge:     28,   //days
			LocalTime: true,
			Compress:  false, // disabled by default
		}
		l := len(args)
		switch l {
		case 1:
			lj.MaxSize = args[l]
		case 2:
			lj.MaxBackups = args[l]
		case 3:
			lj.MaxAge = args[l]
		}
		w = lj
	}
	ctx := zerolog.New(w).With().Timestamp()
	switch level {
	case "debug":
		zerolog.SetGlobalLevel(zerolog.DebugLevel)
		ctx = ctx.Caller()
	case "info":
		zerolog.SetGlobalLevel(zerolog.InfoLevel)
	case "warn":
		zerolog.SetGlobalLevel(zerolog.WarnLevel)
	case "Error":
		zerolog.SetGlobalLevel(zerolog.ErrorLevel)
	}
	Logger = ctx.Logger()
}
